package edu.yngsxy.demo.controller;

import edu.yngsxy.demo.model.Result;
import edu.yngsxy.demo.model.TUser;
import edu.yngsxy.demo.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.Pattern;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result<TUser> login(@Pattern(regexp = "^\\S{2,16}$") String userName,@Pattern(regexp = "^\\S{6,16}$")  String password, HttpSession session){
        TUser tUser = userService.login(userName,password);
        if(tUser==null){
            return Result.error("用户名或密码错误");
        }
        session.setAttribute("loginuser",tUser);
        return Result.success(tUser);
    }


    @GetMapping("/userinfo")
    public Result<TUser> userinfo(HttpSession session){
        TUser tUser = (TUser) session.getAttribute("loginuser");
        return Result.success(tUser);
    }

    @GetMapping("loginout")
    public Result loginout(HttpSession session){
        session.removeAttribute("loginuser");
        return Result.success();
    }

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{2,16}$")String userName,@Pattern(regexp = "^\\S{6,16}$")String password){
       if(!userService.isUseridValid(userName)){
           return Result.error("用户名不可用");
       }
       if(userService.registerUser(userName,password)){
           return Result.success("注册成功");
       }
       return Result.error("注册失败");
    }

    @PutMapping("/modifyUser")
    public Result modifyUser(@RequestBody @Validated TUser user){
        boolean t = userService.modifyUser(user);
        if(t){
            return Result.success("修改成功");
        }else{
            return Result.error("修改失败");
        }
    }
}
